package com.atguigu.day06;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink06_Timer_Exec {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.将数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });


        //5.将相同id的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = map.keyBy("id");


        //6.监控水位传感器的水位值，如果水位值在五秒钟之内连续上升，则报警，并将报警信息输出到侧输出流。

        //当水位没有上升的时候，就不再监控，水位再次上升的时候再重新监控5s内的情况
        /**
         * 要保存的东西：1.上一次的水位 2.定时器的定时时间
         * 要判断的东西：1.当前水位与上一次水位对比判断是否上升 2.判断定时器是否注册
         * 要更新的东西：1.更新上一次水位 2.更新定时器时间
         */
        SingleOutputStreamOperator<String> result = keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
            //保存上一次的水位
            private Integer lastVc = Integer.MIN_VALUE;

            //保存定时时间
            private Long timer = Long.MIN_VALUE;

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //1.首先判断水位是否上升
                if (value.getVc() > lastVc) {
                    //水位上升
                    //2.判断5s的定时器是否已经被之前的数据注册，如果没有注册则自己是5s内的第一条数据，需要注册一个新的定时器
                    if (timer == Long.MIN_VALUE) {
                        //定时器没有被注册
                        //2.1注册定时器
                        System.out.println("注册定时器"+ctx.getCurrentKey()+"："+ctx.timerService().currentProcessingTime());
                        timer = ctx.timerService().currentProcessingTime() + 5000;
                        ctx.timerService().registerProcessingTimeTimer(timer);
                    }
                } else {
                    //3.水位没有上升
                    //先判断是否注册定时器，如果注册了则删除定时器
                    if (timer != Long.MIN_VALUE) {
                        System.out.println("删除定时器"+ctx.getCurrentKey());
                        ctx.timerService().deleteProcessingTimeTimer(timer);
                        //重置定时器时间
                        timer = Long.MIN_VALUE;
                    }
                }
                //更新上一次水位
                lastVc = value.getVc();
                out.collect(value.toString());
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                //获取侧输出流
                ctx.output(new OutputTag<String>("warning!"){}, "警报！！！水位5S连续上升！！！");

                System.out.println("重置定时器");
                //定时器触发了，为了下一次能够再次注册定时器，则将定时器的时间恢复成默认值
                timer = Long.MIN_VALUE;
            }
        });

        result.print();

        result.getSideOutput(new OutputTag<String>("warning!") {
        }).print("报警信息");

        env.execute();

    }
}
